package com.luo.security;

import com.alibaba.fastjson.JSON;
import com.luo.entity.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Zoro
 * @date 2021年08月31
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        if (isAjaxRequest(httpServletRequest)) {
            Result result = new Result(false, "无权访问", "403");
            String json = JSON.toJSONString(result);
            httpServletResponse.getWriter().print(json);
        } else {
            httpServletRequest.getRequestDispatcher("/pages/error/403.html").forward(httpServletRequest, httpServletResponse);
        }
    }

    /**
     * 判断是否为ajax请求
     */
    private static boolean isAjaxRequest(HttpServletRequest request) {
        if (request.getHeader("accept").indexOf("application/json") > -1
                || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest"))) {
            return true;
        }
        return false;
    }


}
